package com.hanbang.chu_xing_gao_zhao.view_me;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.CommentData;
import com.hanbang.chu_xing_gao_zhao.entity.DynamicData;
import com.hanbang.chu_xing_gao_zhao.entity.DynamicHorozontalListviewData;
import com.hanbang.chu_xing_gao_zhao.entity.SharedData;
import com.hanbang.chu_xing_gao_zhao.myview.GridViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SharedUtil;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicBodyActivity;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicManageHome;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.ImageStringUtils;
import com.hanbang.chu_xing_gao_zhao.view_public.DynamicCommentActivity;
import com.hanbang.cxgz_2.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 我的动态
 */
public class MeDynamicActivity extends BaseActivity {
    private ArrayList<DynamicData> listData = new ArrayList<DynamicData>();
    private PullToRefreshListView listView;
    private ListViewAdapter adapter;
    private int pageIndex = 1;
    private int pageSize = 10;
    int id;


    /**
     * 记住分享的位置
     */
    private int mPosition;

    /**
     * 图片展示集合
     */
    private ArrayList<DynamicHorozontalListviewData> hListData = new ArrayList<DynamicHorozontalListviewData>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.me_dynamic);

        initView();
        setOnClickListener();
    }

    /**
     * 初始化view
     */
    private void initView() {
        setTitleMore(View.VISIBLE, View.INVISIBLE, "我的动态", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));


        Intent intent = getIntent();
//        id = intent.getIntExtra("id", 0);
        id = 105;

        listView = (PullToRefreshListView) findViewById(R.id.lv_me_dynamic_list);
        //初始化评论列表
        adapter = new ListViewAdapter(listData);
        listView.setAdapter(adapter);

        //调评论接口
        RequestParams paramsB = new RequestParams();
        paramsB.addBodyParameter("telphone", userData.getTelphone());
        paramsB.addBodyParameter("password",userData.getPassword());
        paramsB.addBodyParameter("id", id + "");
        paramsB.addBodyParameter("type", 4 + "");
        paramsB.addBodyParameter("pageIndex", pageIndex + "");
        paramsB.addBodyParameter("pageSize", pageSize + "");
        getHttpList(HttpInterfaces.Comment_List, paramsB);

    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        //上下刷新
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                listData.clear();

                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userData.getTelphone());
                params.addBodyParameter("password", userData.getPassword());
                params.addBodyParameter("id", id + "");
                params.addBodyParameter("type", 4 + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("pageSize", pageSize + "");
                getHttpList(HttpInterfaces.Comment_List, params);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;

                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userData.getTelphone());
                params.addBodyParameter("password", userData.getPassword());
                params.addBodyParameter("id", id + "");
                params.addBodyParameter("type", 4 + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("pageSize", pageSize + "");
                getHttpList(HttpInterfaces.Comment_List, params);
            }
        });
    }

    /**
     * 处理监听
     */
    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                default:
                    break;
            }
        }
    };


    /**
     * 获取我的订单
     */
    private void getHttpList(String url, RequestParams params) {
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);

                    //获取列表

                    int result = json.getInt("Result");
                    if (result == 0) {
                        JSONArray data = json.getJSONArray("list");

                        if (data.length() == 0) {
                            MyToast.show(MeDynamicActivity.this, "没有更多内容", 1);
                        }
                        listData.addAll(JsonHelper.parseCollection(data, ArrayList.class, DynamicData.class));
                        adapter.notifyDataSetChanged();
                        listView.onRefreshComplete();
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class ListViewAdapter extends BaseAdapter {

        public ArrayList<DynamicData> list = new ArrayList<DynamicData>();

        private int positionShare = -1;
        private int feedIdShare = -1;

        public ListViewAdapter(ArrayList<DynamicData> listData) {

            this.list = listData;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public DynamicData getItem(int position) {

            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                convertView = getLayoutInflater().inflate(R.layout.item_dynamic_listview, null);
                UiUtils.applyFont(convertView);
                viewHolder = new ViewHolder();

                // 子控件初始化
                viewHolder.imageId = (ImageView) convertView.findViewById(R.id.im_item_listview_dynamic_imageId);
                viewHolder.vip = (ImageView) convertView.findViewById(R.id.iv_item_dynamic_listview_vip);
                viewHolder.name = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_name);
                viewHolder.time = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_time);
//                viewHolder.phone = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_phone); //手机型号取消显示
                viewHolder.group = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_group);
                viewHolder.describe = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_describe);
                viewHolder.addressed = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_addressed);
                viewHolder.transmit = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_share);
                viewHolder.comment = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_comment);
                viewHolder.praise = (TextView) convertView.findViewById(R.id.tv_item_listview_dynamic_praise);

                viewHolder.transmitParent = (LinearLayout) convertView.findViewById(R.id.ll_item_dynamic_listview_transmit);
                viewHolder.commentParent = (LinearLayout) convertView.findViewById(R.id.ll_item_dynamic_listview_comment);
                viewHolder.praisetParent = (LinearLayout) convertView.findViewById(R.id.ll_item_dynamic_listview_likecount);
                viewHolder.attentionParent = (LinearLayout) convertView.findViewById(R.id.ll_item_dynamic_listView_attention);
                viewHolder.attentionParent.setVisibility(View.GONE);

                viewHolder.attentionFriend = (ImageView) convertView
                        .findViewById(R.id.cb_item_dynamic_listView_attention);

                viewHolder.attentionFriendText = (TextView) convertView
                        .findViewById(R.id.tv_item_dynamic_listView_attention_text);

                viewHolder.gridView = (GridViewForScrollView) convertView.findViewById(R.id.item_dynamic_gridView);

                convertView.setTag(viewHolder);// 把现有有item对象存起来
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            final DynamicData data = getItem(position);

            // 加载网络图片
            bitmapUtils.display(viewHolder.imageId, SystemTools.getHttpFileUrl(data.getAvatar()));
            viewHolder.name.setText(data.getUser_name());
            // 设置时间
            viewHolder.time.setText(StringUtils_2.getTime(data.getAdd_time()));

            //手机型号取消显示
//            viewHolder.phone.setText(data.getPhone());

            viewHolder.group.setText(String.valueOf(data.getFriendcount()));

            StringBuffer sb = new StringBuffer();
            // 把表情转义显示
            if (data.getText() != null) {
                sb.append(data.getText().toString());

                viewHolder.describe.setText(ImageStringUtils.getEmotionContent(MeDynamicActivity.this, viewHolder.describe,
                        sb.toString()));

                sb.delete(0, sb.length());
            }
            // 指定一个特殊字符，截取它后面的内容。（服务器返回过来的日期为：**省-**市-**区-**街道），显示时只显示城市+街道。

//            String symbol = "-";
            if (data.getPosition() != null) {
                viewHolder.addressed.setText(data.getPosition());
            }

            viewHolder.transmit.setText(String.valueOf(data.getSharecount()));
            viewHolder.comment.setText(String.valueOf(data.getCommentcount()));
            viewHolder.praise.setText(String.valueOf(data.getLikecount()));
            if (!data.isIs_vip()) {

                viewHolder.vip.setVisibility(View.GONE);
            }

            if (data.getFollow() == 0) {

                viewHolder.attentionFriendText.setText("关注");
                viewHolder.attentionFriend.setSelected(false);

            } else {
                viewHolder.attentionFriendText.setText("已关注");
                viewHolder.attentionFriend.setSelected(true);
            }

            viewHolder.gridView.setFocusable(false);
            viewHolder.gridView.setEnabled(false);
            viewHolder.gridView.setFocusableInTouchMode(false);

            viewHolder.gridView.setAdapter(new GridViewAdapter(data.getId(), data));

            /**
             * 头像点击跳转
             */
            viewHolder.imageId.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Intent intent = new Intent(MeDynamicActivity.this, DynamicManageHome.class);
                    // Bundle bundle=new Bundle();
                    // bundle.putSerializable("imageId", hListData);
                    // intent.putExtras(bundle);
                    startActivity(intent);

                }
            });

            /**
             * 打开分享
             */
            viewHolder.transmitParent.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
//                    SharedUtil.shered(DynamicActivity.this, data.getUser_name(), data.getText(), "http://www.baidu.com", SystemTools.getHttpFileUrl(data.getAvatar()));
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("telphone", userData.getTelphone());
                    params.addBodyParameter("password", userData.getPassword());
                    params.addBodyParameter("feed_id", data.getId() + "");
                    SharedUtil.shered(MeDynamicActivity.this, new SharedData(data.getUser_name(), data.getText(), "http://www.baidu.com", SystemTools.getHttpFileUrl(data.getAvatar()), params));
                    mPosition = position;

                }
            });


            /**
             * 赞的监听
             */
//            viewHolder.praisetParent.setOnClickListener(new OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//
//                    RequestParams params = new RequestParams();
//
//                    params.addBodyParameter("telphone", userData.getTelphone());
//                    params.addBodyParameter("password",userData.getPassword());
//
//                    params.addBodyParameter("id", data.getId() + "");
//                    params.addBodyParameter("type", 7 + "");
//                    getVisit("提交成功", HttpInterfaces.Like_Add, params, "正在提交", praiseType, position);
//
//                }
//            });

            /**
             * 评价的监听
             */
            viewHolder.commentParent.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MeDynamicActivity.this, DynamicCommentActivity.class);
                    intent.putExtra("position", position);
                    intent.putExtra("feed_id", data.getId());
                    startActivityForResult(intent, 888);

                }
            });

            //点出评论跳入动态正文
            viewHolder.describe.setOnClickListener(new OnClickListener() {
                public ArrayList<DynamicHorozontalListviewData> list = new ArrayList<DynamicHorozontalListviewData>();

                @Override
                public void onClick(View v) {

                    list.clear();
                    for (int i = 0; i < hListData.size(); i++) {

                        if (hListData.get(i).getFeed_id() == listData.get(position).getId()) {

                            list.add(hListData.get(i));
                        }
                    }

                    Intent intent = new Intent(MeDynamicActivity.this, DynamicBodyActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("imageId", list);

                    bundle.putSerializable("data", data);

                    intent.putExtra("listPosition", position);

                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });


            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            // 子控件主要是里面的数据
            private ImageView imageId;
            private ImageView vip;
            private TextView name;
            private TextView time;
            //            private TextView phone;
            private TextView group;
            private TextView describe;
            private TextView addressed;
            private TextView transmit;// 转发
            private TextView comment;
            private TextView praise;// 赞
            private GridViewForScrollView gridView;
            /**
             * 关注朋友
             */
            private ImageView attentionFriend;
            private TextView attentionFriendText;

            private LinearLayout transmitParent;
            private LinearLayout commentParent;
            private LinearLayout praisetParent;
            private LinearLayout attentionParent;


        }

    }


    /**
     * horizaontal listView adapter
     *
     * @author Administrator
     */
    class GridViewAdapter extends BaseAdapter {
        public ArrayList<DynamicHorozontalListviewData> list = new ArrayList<DynamicHorozontalListviewData>();
        private int itemId;
        private DynamicData user = new DynamicData();


        public GridViewAdapter(int itemId, DynamicData user) {
            this.itemId = itemId;
            this.user = user;

            /**
             * 首页只显示3张图片
             */
            int x = 0;
            for (int i = 0; i < hListData.size(); i++) {

                if (hListData.get(i).getFeed_id() == itemId) {

                    this.list.add(hListData.get(i));
                    x++;
                }

            }

        }

        @Override
        public int getCount() {

            return list.size() > 3 ? 3 : list.size();
        }

        @Override
        public DynamicHorozontalListviewData getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            UiUtils.applyFont(convertView);
            ViewHolder viewHolder;

            if (convertView == null) {// 是空加载
                convertView = getLayoutInflater().inflate(R.layout.item_dycamic_horizontal_listview, null);

                viewHolder = new ViewHolder();

                viewHolder.goodsImage = (ImageView) convertView.findViewById(R.id.iv_item_shoppingcart_recommend_image);

                convertView.setTag(viewHolder);
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            DynamicHorozontalListviewData data = getItem(position);

            //

            // 加载网络图片
            bitmapUtils.display(viewHolder.goodsImage, SystemTools.getHttpFileUrl(data.getImg_url()));


            viewHolder.goodsImage.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Intent intent = new Intent(MeDynamicActivity.this, DynamicBodyActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("imageId", list);

                    bundle.putSerializable("data", user);

                    intent.putExtra("listPosition", position);

                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            });

            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            private int id;
            private ImageView goodsImage; // 产品图片
            private String imageUrl;

        }

    }

}
